import 'dart:io';
import 'dart:math';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:speak_text/rand_reader.dart';
import 'package:speak_text/spk.dart';

class MyData extends ChangeNotifier {
  List<String> _content = List.empty(growable: true);
  List<String> _rand = List.empty();
  double _speed = 1.0;
  int _idx = -1;
  final _none = '没有内容';
  static dynamic voices;

  List<String> get content => _content;
  List<String> get rand => _rand;
  int get index => _idx;

  double get speed => _speed;
  void setSpeed(double spd) {
    _speed = spd;
    notifyListeners();
  }

  void appendContent(String s) {
    if (_content.contains(s)) return;
    _content.add(s);
    notifyListeners();
  }

  void removeContent(int idx) {
    if (_content.length <= idx) return;
    _content.removeAt(idx);
    notifyListeners();
  }

  void setContent(List<String> list1) {
    _content = list1;
    _idx = -1;
    notifyListeners();
  }

  void setRand(List<String> list1) {
    _rand = list1;
    _idx = -1;
    notifyListeners();
  }

  String next() {
    if (_rand.isEmpty) {
      return _none;
    }
    _idx++;
    if (_idx >= _rand.length) {
      _idx = _rand.length - 1;
    } else if (_idx < 0) {
      _idx = 0;
    }
    notifyListeners();
    return _rand[_idx];
  }

  String last() {
    if (_rand.isEmpty) {
      return _none;
    }
    _idx--;
    if (_idx <= 0) {
      _idx = 0;
    } else if (_idx >= _rand.length) {
      _idx = _rand.length - 1;
    }
    notifyListeners();
    return _rand[_idx];
  }

  String head() {
    if (_rand.isEmpty) {
      return _none;
    }
    _idx = 0;
    notifyListeners();
    return _rand[_idx];
  }

  String tail() {
    if (_rand.isEmpty) {
      return _none;
    }
    _idx = _rand.length - 1;
    notifyListeners();
    return _rand[_idx];
  }
}

bool once = true;
void main() {
  ttsInit().then((value) {
    runApp(
      MultiProvider(
        providers: [
          ChangeNotifierProvider(create: (_) => MyData()),
        ],
        child: const MyApp(),
      ),
    );
  });
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    if (once) {
      ttsInit();
      once = false;
    }
    return MaterialApp(
      title: 'Speak line words',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Speak line words'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  List<String> randList(List<String> list1) {
    var rand1 = Random(DateTime.now().microsecond);
    for (int i = 0; i < list1.length - 1; i++) {
      // 从 i+1 到 length-1
      var max1 = list1.length - 2 - i;
      int n = max1;
      if (max1 > 1) {
        n = rand1.nextInt(max1);
        //n = rand1.nextInt(max1) % (max1+1);
      }

      print('$i , $n(Max:$max1), ${list1.length}');
      String tmp = list1[i];
      list1[i] = list1[i + n + 1];
      list1[i + n + 1] = tmp;
    }
    return list1;
  }

  @override
  Widget build(BuildContext context) {
    TextEditingController input1 = TextEditingController();
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Column(
        children: [
          const Divider(),
          TextField(
            onSubmitted: (value) {
              if (value.trim().isEmpty) {
                return;
              }
              Provider.of<MyData>(context, listen: false).appendContent(value);
            },
            controller: input1,
            decoration: const InputDecoration(
              labelText: '词语或句子:',
              hintText: '输入内容将保存到本机存储',
            ),
          ),
          Wrap(
            children: [
              ElevatedButton(
                onPressed: () {
                  if (input1.text.trim().isEmpty) {
                    return;
                  }
                  Provider.of<MyData>(context, listen: false)
                      .appendContent(input1.text);
                },
                child: const Text('输入'),
              ),
              ElevatedButton(
                onPressed: () async {
                  //shared preference
                  var store = await SharedPreferences.getInstance();
                  await store.setStringList('content',
                      Provider.of<MyData>(context, listen: false).content);
                },
                child: const Text('保存'),
              ),
              ElevatedButton(
                onPressed: () async {
                  FilePickerResult? result =
                      await FilePicker.platform.pickFiles();

                  if (result == null) {
                    return;
                  }
                  File file = File(result.files.single.path!);
                  var lines = await file.readAsLines();
                  Provider.of<MyData>(context, listen: false).setContent(lines);
                },
                child: const Text('导入'),
              ),
              ElevatedButton(
                onPressed: () async {
                  //shared preference
                  var store = await SharedPreferences.getInstance()
                    ..reload();
                  var list1 = store.getStringList('content');
                  if (list1 != null) {
                    Provider.of<MyData>(context, listen: false)
                        .setContent(list1);
                  }
                },
                child: const Text('恢复'),
              ),
              ElevatedButton(
                onPressed: () async {
                  List<String> list1 = List.empty(growable: true);
                  Provider.of<MyData>(context, listen: false).setContent(list1);
                },
                child: const Text('清空'),
              ),
              ElevatedButton(
                onPressed: () {
                  List<String> list1 =
                      Provider.of<MyData>(context, listen: false).content;
                  Provider.of<MyData>(context, listen: false)
                      .setRand(randList(list1));
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => MyReader(
                          mainContext: context,
                        ),
                      ));
                },
                child: const Text('乱序阅读'),
              ),
            ],
          ),
          Expanded(
            child: SingleChildScrollView(
              physics: const BouncingScrollPhysics(),
              child: Table(
                border: const TableBorder(top: BorderSide(),horizontalInside: BorderSide(),bottom: BorderSide()),
                defaultVerticalAlignment: TableCellVerticalAlignment.middle,
                children: () {
                  var ret = List<TableRow>.empty(growable: true);
                  var list1 = Provider.of<MyData>(context).content;
                  int i = 1;
                  for (var w in list1) {
                    TableRow r1 = TableRow(
                      children: [
                      Text(
                        i.toString(),
                        textAlign: TextAlign.center,
                      ),
                      Text(
                        w,
                        textAlign: TextAlign.left,
                      ),
                      TextButton(
                        onPressed: (int idx) {
                          return () {
                            Provider.of<MyData>(context, listen: false)
                                .removeContent(idx);
                          };
                        }(i - 1),
                        child: const Text("删除"),
                      ),
                    ]);
                    i++;
                    ret.add(r1);
                  }
                  return ret;
                }(),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
